<?php

class LotteryController extends Controller{

	

	/**
	Lottery Page
	**/
	public function index(){

		$smaryt = $this->getSmarty();

        $smaryt->assign ( 'pagesets', $this->headerDatas() );

        require_once SERVICE . DS  . 'LotteryService.class.php';

        $logined = false;
        if( isset($_SESSION['user'])) {
        	$logined = true;
        }


        $msg = "You have not yet participate in the lottery today,Oh, and pass almost Award!";
        if(!$logined){
            $msg = "You need sub our message or login in to draw! <a herf='emailsub' >Sub Email</a>";
        }

        $lotteryService = new lotteryService( $this->getDB ());
        $records = $lotteryService->lotteryRecords(10);


        $smaryt->assign ( 'logined', $logined);
        $smaryt->assign ( 'msg', $msg);
        $smaryt->assign ( 'records', $records);

        $smaryt->display("lottery.tpl");

	}


	 public function headerDatas(){
        require_once COMMON . DS  . 'Constant.class.php';
        $js = array(WEBSITE_URL."public/assets/js/jquery.validationEngine-zh.js",WEBSITE_URL."public/assets/js/jquery.validationEngine.js");
        $css = array(WEBSITE_URL."public/assets/css/validationEngine.jquery.css");
        $pagesets = array("seo"=>Constant::$seoarray,"js"=>$js,"css"=>$css,"nav"=>Constant::getNav());

        return $pagesets;
    }

    public function draw(){

        // To config;===========
        // cost to draw;
        $payCost = 50;
        // points up limit;
        $upLimit = 500;
        // none point lottery item
        $noneIndex = 0;

        /* 
         * 奖项数组 
         * 是一个二维数组，记录了所有本次抽奖的奖项信息， 
         * 其中id表示中奖等级，prize表示奖品，v表示中奖概率。 
         * 注意其中的v必须为整数，你可以将对应的 奖项的v设置成0，即意味着该奖项抽中的几率是0， 
         * 数组中v的总和（基数），基数越大越能体现概率的准确性。 
         * 本例中v的总和为100，那么平板电脑对应的 中奖概率就是1%， 
         * 如果v的总和是10000，那中奖概率就是万分之一了。 
         *  
         */  
        $total_Lottery = array(   
            '0' => array('id'=>1,'prize'=>'0', 'type'=>2  ,'v'=>100, 'angle'=> array(45, 90)),   
            '1' => array('id'=>2,'prize'=>'0', 'type'=>2,'v'=>30,'angle'=> array(180, 225)),   
            '2' => array('id'=>3,'prize'=>'0', 'type'=>2,'v'=>40, 'angle'=> array(31, 60)),   
            '3' => array('id'=>4,'prize'=>'0', 'type'=>2,'v'=>5, 'angle'=> array(315, 360)),   
            '4' => array('id'=>5,'prize'=>'0', 'type'=>1,'v'=>4, 'angle'=> array(0, 45)),   
            '5' => array('id'=>6,'prize'=>'60', 'type'=>1,'v'=>2, 'angle'=> array(95, 130)),
            '6' => array('id'=>7,'prize'=>'0', 'type'=>1,'v'=>40, 'angle'=> array(225, 270)), 
            '7' => array('id'=>8,'prize'=>'0', 'type'=>1,'v'=>60, 'angle'=> array(270, 315)),
            '8' => array('id'=>9,'prize'=>'0', 'type'=>1,'v'=>100, 'angle'=> array(135, 180)),    
        ); 


        require_once SERVICE . DS  . 'LotteryService.class.php';
        require_once SERVICE . DS  . 'admin/UsersService.class.php';

        $result = array();
        $msg = false;
        $couldDraw = false;

        $lotteryService = new lotteryService( $this->getDB ());

         $logined = false;
        if( isset($_SESSION['user'])) {
            $logined = true;
        }

        if(!$logined){
            $result['error']  = '1';
            $result['msg'] = "You need sub our message or login in to draw! <a herf='emailsub' >Sub Email</a>!";
            echo json_encode($result);
            exit(0);
        }

        $user = $_SESSION['user'];


        $userService  = new UsersService($this->getDB());
        $user = $userService->getUserInfoByID('3f0fed062523b65f62f47c3ae4dc88cf');

        $userInfo = $userService->getUserInfoByID($user->userid);

        if($userInfo && $userInfo->points && $userInfo->points < 20){
            $result['error']  = '1';
            $result['msg'] = "Your points is not enough!";
            echo json_encode($result);
            exit(0);
        }else
        {
            


            foreach ($total_Lottery as $key => $val) {   
                $arr[$val['id']] = $val['v'];   
            }

            $rid = $this->get_rand($arr); //根据概率获取奖项id  

            
            $res = $total_Lottery[$rid-1]; //中奖项

            //记录中奖记录
            $pointChange = 0 - $payCost;

            $earnedPoint = $res['prize'];

            if($earnedPoint + $userInfo->points > $upLimit){
                $res = $total_Lottery[$noneIndex];
                $earnedPoint = $res['prize'];
            }

            if($res['type'] == 2){
                $pointChange = $pointChange + $earnedPoint;
            }

            $userService->updateUserPoints($userInfo->userid, $pointChange);

            //Record points shopping...
            $userService->addPointRecord(array('id' => uniqid(), 'userid'=>$userInfo->userid, 'username' => $userInfo->username,
                                            'record_type' => '1', 'points' => $payCost, 'create_time'=> array( date("Y-m-d G:i:s"),'%Y-%m-%d %H:%i:%s'), 'points_type'=>4,
                                            'points_desc' => 'Pay '.$payCost.' points to draw.'));

            if($earnedPoint > 0){
                if($res['type'] == 2){
                    $userService->addPointRecord(array('id' => uniqid(), 'userid'=>$userInfo->userid, 'username' => $userInfo->username,
                                                'record_type' => '0', 'points' => $earnedPoint, 'create_time'=> array( date("Y-m-d G:i:s"),'%Y-%m-%d %H:%i:%s'), 'points_type'=>0,
                                                'points_desc' => 'Earn '.$earnedPoint.' points to draw.'));
                }

                //Record draw
                $userService->addDrawRecord(array('id'=> uniqid(), 'userid'=> $userInfo->userid, 'username'=> $userInfo->username, 
                                            'lottery_result_type'=> $res['type'], 'lottery_result' => $earnedPoint, 
                                            'create_time'=> array( date("Y-m-d G:i:s"),'%Y-%m-%d %H:%i:%s')));    
            }
            


            $angle = rand($res['angle'][0], $res['angle'][1]);
            $result = array('awards'=> $earnedPoint, 'angle'=> 360*5 + $angle); 
            echo json_encode($result);    
        }

    	
    }

    /* 
 * 经典的概率算法， 
 * $proArr是一个预先设置的数组， 
 * 假设数组为：array(100,200,300，400)， 
 * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内，  
 * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间， 
 * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。 
 * 这样 筛选到最终，总会有一个数满足要求。 
 * 就相当于去一个箱子里摸东西， 
 * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。 
 */  
private function get_rand($proArr) {   
    $result = '';    
    //概率数组的总概率精度   
    $proSum = array_sum($proArr);    
    //概率数组循环   
    foreach ($proArr as $key => $proCur) {   
        $randNum = mt_rand(1, $proSum);   
        if ($randNum <= $proCur) {   
            $result = $key;   
            break;   
        } else {   
            $proSum -= $proCur;   
        }         
    }   
    unset ($proArr);    
    return $result;   
}   
  
}

?>